const http = require('http');
const url = require('url');
const mime = require('./mime.js');
const path = require('path');
const fs = require('fs');
const util = require('util');

const formidable = require('formidable');

const root = __dirname;
const index = 'index.html';

http.createServer((req, res) => {
    let realPath = url.parse(req.url).pathname;

    if (realPath === '/upload' && req.method.toLowerCase() === 'post') {
        const form = new formidable.IncomingForm();
        form.uploadDir = root;
        form.parse(req, function (err, fields, files) {
            res.writeHead(200, { 'content-type': 'text/plain' });
            res.write('received upload:\n\n');
            res.end(util.inspect({ fields: fields, files: files }));
        });
        return;
    }

    if (realPath.charAt(realPath.length - 1) === "/") {
        realPath += index;
    }

    realPath = root + realPath;

    let ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';

    console.log(realPath);

    fs.exists(realPath, function (exists) {
        console.log('path.exists--%s', exists);
        if (!exists) {
            res.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            res.write('This request URL ' + realPath + ' was not found on this server.');
            res.end();
        } else {
            fs.readFile(realPath, 'binary', function (err, file) {
                if (err) {
                    res.writeHead(500, {
                        'Content-Type': 'text/plain'
                    })
                    res.end(err + '\n');
                } else {
                    const contentType = mime[ext] || 'Content-Type';
                    res.writeHead(200, {
                        'Content-Type': contentType
                    });
                    res.write(file, 'binary');
                    res.end();
                }
            });
        }
    });
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');